package day01;

import java.util.Arrays;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/3/13 21:48
 * 希尔排序
 */
public class ShellSort {

    public static void main(String[] args) {
        int[] arr = {2, 4, 1, 5, 3, 9, 7, 6, 8};
        System.out.println("排序前:" + Arrays.toString(arr));
        // shellSort(arr);
        shellSort02(arr);
        System.out.println("排序后:" + Arrays.toString(arr));
    }

    public static void shellSort(int[] arr) {
        for (int gap = arr.length / 2; gap > 0; gap /= 2) {
            for (int i = gap; i < arr.length; i++) {
                // 对每个分组进行冒泡排序
                for (int j = i - gap; j >= 0; j -= gap) {
                    if (arr[j] > arr[j + gap]) {
                        int temp = arr[j];
                        arr[j] = arr[j + gap];
                        arr[j + gap] = temp;
                    }
                }
            }
        }
    }


    public static void shellSort02(int[] arr) {
        int N = arr.length;
        // 分组，最开始的增量为数组的一半
        for(int gap = N / 2; gap > 0; gap /= 2) {
            // 对每个分组进行插入排序
            for (int i = gap; i < N; i++) {
                int inserted = arr[i];
                int j;
                for (j = i - gap; j >=0 && arr[j] > inserted; j -= gap) {
                    arr[j + gap] = arr[j];
                }
                arr[j + gap] = inserted;
            }
        }
    }
}
